package com.rzico.quartz.job;

import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Product;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ProductService;
import com.rzico.core.entity.*;
import com.rzico.core.plugin.market.MarketJDPlugin;
import com.rzico.core.service.*;
import com.rzico.market.entity.MarketProduct;
import com.rzico.market.service.MarketProductService;
import com.rzico.util.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 京东商品信息每日更新
 */
public class JDApiProductTask implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    protected SysPluginService sysPluginService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    protected MarketProductService marketProductService;

    @Autowired
    public MarketJDPlugin marketJDPlugin;

    @Autowired
    private ProductService productService;



    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        boolean lastOperate = true;//上一次更新商品信息的位置：true-商品库（wx_product），false-商品池（market_product）
        String startTimes = "0";//上一次更新的位置
        try {
            if (sysJob.getExecStatus().equals(1)) {
                if ("0".equals(sysJob.getExecErrDesc()) && !sysJob.getJobDesc().contains("开始执行")) {
                    //不能重复执行
                    return;
                }
            }
            //根据当前日期及任务描述，判断当天是否已经全部成功更新数据
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
            boolean sameDay = fmt.format(new Date()).equals(fmt.format(sysJob.getModifyDate()));//当前时间与上一次更新时间是否为同一天
            /*
                获取上一次是更新商品库的京东商品信息还是商品池的商品信息，再获取上一次更新至第几次循环，0表示上一次更新已全部更新完成
             */
            if (StringUtils.isNotEmpty(sysJob.getExecErrDesc()) && !"0".equals(sysJob.getExecErrDesc())) {
                if (sysJob.getExecErrDesc().contains("pool")) {//上一次更新至商品池
                    lastOperate = false;
                }
                String[] indexNum = sysJob.getExecErrDesc().split("-");
                startTimes = indexNum[1];
            }
            if (sameDay && "0".equals(sysJob.getExecErrDesc()) && !sysJob.getJobDesc().contains("开始执行")) {
                return;
            }

            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 这里写你要做的事情
            //获取京东授权token
            String token = JDServiceUtils.refrash_token();
            /**
             * 获取当前商户的信息
             */
            String mchId = "";
            Long enterpriseId = 0L;
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("name","葫芦派");
            List<Enterprise> enterpriseList= enterpriseService.selectList(param);
            if (0 < enterpriseList.size()) {
                mchId = enterpriseList.get(0).getMchId();
                enterpriseId = enterpriseList.get(0).getId();
            }
            /**
             * 第一步，查看京东商品插件,设置token属性
             */
            SysPlugin sysplugin = sysPluginService.findByPlugin(mchId, "marketJDPlugin");
            marketJDPlugin.setToken(sysplugin, token, mchId);
            /**
             * 第二步，将京东商品信息保存至数据库
             */
            marketProductService.saveJDProductInfo(sysplugin);
            /**
             * 第三步，已上架到商品库（wx_product）中的京东商品sku每天定时检查
             */
            if (lastOperate) {
                //每次更新10条数据
                Map<String, Object> productParams = new HashMap<String, Object>();
                productParams.put("sn", "jd-");
                List<Product> productList = productService.selectList(productParams);
                if (0 < productList.size()) {
                    int size = productList.size();
                    int divisor = 10;
                    int times = size / divisor;//每次更新10条，取共更新多少次
                    int remainder = size % divisor;//求余数，即最后一次更新多少条
                    if (0 != remainder) {//若余数不为0，则次数+1
                        times += 1;
                    }
                    int lastTimes = Integer.valueOf(startTimes);
                    for (int i = 1 ; i <= times; i ++) {
                        //判断是否是上一次已更新完成，若已完成则跳过直接进行下一次
                        if (i <= lastTimes) {
                            continue;
                        }
                        List<Product> updateProductList = new ArrayList<Product>();
                        sysJob.setExecErrDesc("db-" + i);
                        //若最后一次不满10条记录，有多少条取多少条
                        if (0 != remainder && i == times) {
                            for (int j = 0; j < remainder; j ++) {
                                updateProductList.add(productList.get((i - 1) * 10 + j));
                            }
                        } else {
                            updateProductList.add(productList.get((i - 1) * 10));
                            updateProductList.add(productList.get((i - 1) * 10 + 1));
                            updateProductList.add(productList.get((i - 1) * 10 + 2));
                            updateProductList.add(productList.get((i - 1) * 10 + 3));
                            updateProductList.add(productList.get((i - 1) * 10 + 4));
                            updateProductList.add(productList.get((i - 1) * 10 + 5));
                            updateProductList.add(productList.get((i - 1) * 10 + 6));
                            updateProductList.add(productList.get((i - 1) * 10 + 7));
                            updateProductList.add(productList.get((i - 1) * 10 + 8));
                            updateProductList.add(productList.get((i - 1) * 10 + 9));
                        }
                        marketProductService.updateJDProductInfo(sysplugin, enterpriseId, mchId, updateProductList);
                    }
                }
                //将startTimes重置
                startTimes = "0";
            }
            /**
             * 第四步，定时更新京东商品的价格，商品得上下架状态，商品可售性,每次更新
             */
            Map<String, Object> map = new HashMap<String, Object>();
            int size = 50;
            map.put("sn", "jd-");
            map.put("size", size);
            int lastStartIndex = Integer.valueOf(startTimes);
            for (int i = 0 ; i < 10; i ++) {
                if (0 != i) {
                    lastStartIndex += size;
                }
                sysJob.setExecErrDesc("pool-" + lastStartIndex);
                map.put("startNum", lastStartIndex);
                List<MarketProduct> marketProductList = marketProductService.selectList(map);
                if (0 < marketProductList.size()) {
                    marketProductService.updateJDProductInfo(sysplugin, marketProductList);
                    marketProductService.updateJDProductPrice(sysplugin, marketProductList);
                    marketProductService.updateJDProductImage(sysplugin, marketProductList);
                    marketProductService.updateJDProductState(sysplugin, marketProductList);
                    marketProductService.updateJDProductSaleState(sysplugin, marketProductList);
                } else {
                    sysJob.setExecErrDesc("0");
                    break;
                }
            }

            // end

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
        sysJob.setExecStatus(0);
        sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
        sysJobService.updateByPrimaryKeySelective(sysJob);
    }

    }

}
